package com.rustic.server.web;

import cn.xy.base.server.web.AdminWebContext;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 自定义元数据对象处理
 */

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入操作自动填充
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 数据库添加数据有默认填写当前时间
//        metaObject.setValue("createTime", LocalDateTime.now());
//        metaObject.setValue("updateTime",LocalDateTime.now());
        // 判断是否管理端和用户端
        int creatorId;
        int modifierId;
        if (AdminWebContext.getAdminId() != 0) {
            creatorId = AdminWebContext.getAdminId();
            modifierId = AdminWebContext.getAdminId();
        } else {
            creatorId = WebContext.getUserId();
            modifierId = WebContext.getUserId();
        }
        metaObject.setValue("creatorId", creatorId);
        metaObject.setValue("modifierId",modifierId);
    }

    /**
     * 更新的时候自动填充
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateTime", new Date());
        int modifierId;
        if (AdminWebContext.getAdminId() != 0) {
            modifierId = AdminWebContext.getAdminId();
        } else {
            modifierId = WebContext.getUserId();
        }
        metaObject.setValue("modifierId",modifierId);
    }
}
